<!DOCTYPE html>
<html>
<head>
<script src="../resources/js-test.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
    description("Tests concurrent calls to crypto.randomValues from workers.");

    // Generate random values from different 10 workers, and wait until they
    // have all finished.
    var randomValues = {};
    var numRandomValues = 0;
    var NUM_WORKERS = 10;

    self.jsTestIsAsync = true;

    // Asserts that each call to receivedRandomValue() contains unique bytes.
    // The bytes are 100 randomly generated, and as such have an extremely low
    // probability of matching each other.
    function workerGeneratedRandomBytes(bytes)
    { 
        if (bytes.length != 100)
            throw "bytes is not the right length: " + bytes.length;

        var bytesStr = Array.prototype.join.call(bytes, '');

        if (bytesStr in randomValues)
            debug("Generated a duplicate 'random' number: " + bytesStr);
        else
            debug("Received random bytes from worker");

        randomValues[bytesStr] = true;

        if (++numRandomValues == NUM_WORKERS)
            finishJSTest();
    }

    for (var i = 0; i < NUM_WORKERS; ++i) {
        var worker = new Worker('random-values-concurrent.js');
        worker.onmessage = function(event)
        {
            if (event.data instanceof Uint8Array)
                workerGeneratedRandomBytes(event.data);
            else
                debug('[Worker] ' + event.data);
        }
        worker.onerror = function(event)
        {
            debug('Got error from worker: ' + event.message);
            finishJSTest();
        }
    }
</script>

</body>
</html>
